package view.student;

import util.AIService;
import util.MarkdownParser;
import util.FontUtils;
import javax.swing.*;
import javax.swing.text.BadLocationException;
import javax.swing.text.StyledDocument;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * AI学习助手面板
 */
public class AIAssistantPanel extends JPanel {
    private JTextPane chatArea;
    private JTextField inputField;
    private JButton sendButton;
    private JButton clearButton;
    private JComboBox<String> categoryComboBox;
    private boolean isStreaming = false;
    private JPanel quickActionsPanel;
    private JPanel quickActionsButtonPanel;

    public AIAssistantPanel() {
        initComponents();
        setupLayout();
        setupEventListeners();
        initWelcomeMessage();
        // 初始设置快捷问题面板的可见性
        updateQuickActionsPanel();
    }

    private void initComponents() {
        setLayout(new BorderLayout());
        setBackground(new Color(248, 250, 252));

        // 聊天显示区域 - 使用JTextPane支持富文本
        chatArea = new JTextPane();
        chatArea.setEditable(false);
        chatArea.setBackground(new Color(255, 255, 255));
        chatArea.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));
        chatArea.setContentType("text/plain"); // 默认为纯文本，需要时切换到富文本
        FontUtils.setEmojiFont(chatArea); // 设置支持emoji的字体

        // 输入区域
        inputField = new JTextField();
        styleTextField(inputField);

        sendButton = new JButton("发送");
        clearButton = new JButton("清空");

        // 美化按钮
        styleButton(sendButton, new Color(59, 130, 246), Color.WHITE);
        styleModernButton(clearButton, new Color(99, 102, 241));

        // 功能分类
        categoryComboBox = new JComboBox<>();
        categoryComboBox.addItem("自由提问");
        categoryComboBox.addItem("学习方法");
        categoryComboBox.addItem("时间管理");
        categoryComboBox.addItem("学习资源");
        categoryComboBox.addItem("答疑解惑");
        categoryComboBox.addItem("心理支持");

        styleComboBox(categoryComboBox);
    }

    private void setupLayout() {
        // 现代化顶部功能栏
        JPanel topPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        topPanel.setBackground(new Color(255, 255, 255));
        topPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createMatteBorder(0, 0, 1, 0, new Color(229, 231, 235)),
                BorderFactory.createEmptyBorder(15, 20, 15, 20)));

        // 大模型显示
        JLabel modelLabel = createStyledLabel("当前大模型：DeepSeek-V3.1");
        modelLabel.setForeground(new Color(34, 197, 94));
        modelLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 14));
        topPanel.add(modelLabel);
        topPanel.add(Box.createHorizontalStrut(30));

        JLabel categoryLabel = createStyledLabel("类别:");
        topPanel.add(categoryLabel);
        topPanel.add(categoryComboBox);
        topPanel.add(Box.createHorizontalStrut(20));
        topPanel.add(clearButton);

        // 现代化聊天区域
        JScrollPane chatScrollPane = new JScrollPane(chatArea);
        chatScrollPane.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(229, 231, 235), 1),
                BorderFactory.createEmptyBorder(0, 0, 0, 0)));
        chatScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        chatScrollPane.getViewport().setBackground(new Color(255, 255, 255));

        // 现代化快捷功能面板
        quickActionsPanel = createQuickActionsPanel();

        // 现代化底部输入区域
        JPanel inputPanel = new JPanel(new BorderLayout());
        inputPanel.setBackground(new Color(255, 255, 255));
        inputPanel.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createMatteBorder(1, 0, 0, 0, new Color(229, 231, 235)),
                BorderFactory.createEmptyBorder(15, 20, 15, 20)));

        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.RIGHT, 10, 0));
        buttonPanel.setBackground(new Color(255, 255, 255));
        buttonPanel.add(sendButton);

        inputPanel.add(inputField, BorderLayout.CENTER);
        inputPanel.add(buttonPanel, BorderLayout.EAST);

        JPanel bottomPanel = new JPanel(new BorderLayout());
        bottomPanel.setBackground(new Color(248, 250, 252));
        bottomPanel.add(quickActionsPanel, BorderLayout.CENTER);
        bottomPanel.add(inputPanel, BorderLayout.SOUTH);

        add(topPanel, BorderLayout.NORTH);
        add(chatScrollPane, BorderLayout.CENTER);
        add(bottomPanel, BorderLayout.SOUTH);
    }

    private JPanel createQuickActionsPanel() {
        JPanel container = new JPanel(new BorderLayout());
        container.setBackground(new Color(255, 255, 255));
        container.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createMatteBorder(1, 0, 0, 0, new Color(229, 231, 235)),
                BorderFactory.createEmptyBorder(15, 20, 15, 20)));

        JLabel titleLabel = new JLabel("快捷问题");
        titleLabel.setFont(new Font("Microsoft YaHei", Font.BOLD, 14));
        titleLabel.setForeground(new Color(75, 85, 99));
        container.add(titleLabel, BorderLayout.NORTH);

        quickActionsButtonPanel = new JPanel(new GridLayout(2, 2, 10, 10));
        quickActionsButtonPanel.setBackground(new Color(255, 255, 255));
        quickActionsButtonPanel.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));

        // 初始显示学习方法的快捷问题
        updateQuickActions(quickActionsButtonPanel);

        container.add(quickActionsButtonPanel, BorderLayout.CENTER);
        return container;
    }

    private void updateQuickActions(JPanel panel) {
        panel.removeAll();

        String selectedCategory = (String) categoryComboBox.getSelectedItem();

        // 如果选择的是自由提问，隐藏快捷问题面板
        if ("自由提问".equals(selectedCategory)) {
            if (quickActionsPanel != null) {
                quickActionsPanel.setVisible(false);
            }
            return;
        } else {
            if (quickActionsPanel != null) {
                quickActionsPanel.setVisible(true);
            }
        }

        String[] quickQuestions = AIService.getQuickQuestions(selectedCategory);

        Color[] buttonColors = {
                new Color(34, 197, 94), // 绿色
                new Color(59, 130, 246), // 蓝色
                new Color(245, 158, 11), // 橙色
                new Color(139, 92, 246) // 紫色
        };

        for (int i = 0; i < Math.min(4, quickQuestions.length); i++) {
            String question = quickQuestions[i];
            JButton button = new JButton("<html><center>" + question + "</center></html>");
            styleQuickActionButton(button, buttonColors[i]);
            button.addActionListener(_ -> handleQuickQuestion(question));
            panel.add(button);
        }

        panel.revalidate();
        panel.repaint();
    }

    private void setupEventListeners() {
        sendButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                sendMessage();
            }
        });

        inputField.addActionListener(_ -> sendMessage());

        clearButton.addActionListener(_ -> {
            chatArea.setText("");
            initWelcomeMessage();
        });

        // 分类选择监听器 - 更新快捷问题
        categoryComboBox.addActionListener(_ -> {
            // 直接通过成员变量访问快捷操作面板
            updateQuickActionsPanel();
        });
    }

    private void updateQuickActionsPanel() {
        if (quickActionsButtonPanel != null) {
            updateQuickActions(quickActionsButtonPanel);
        }
    }

    private void initWelcomeMessage() {
        try {
            StyledDocument doc = chatArea.getStyledDocument();
            doc.insertString(doc.getLength(), "🤖 AI学习助手：\n", null);
            doc.insertString(doc.getLength(), "您好！我是您的AI学习助手，可以帮助您：\n\n", null);
            doc.insertString(doc.getLength(), "• 制定个性化学习计划\n", null);
            doc.insertString(doc.getLength(), "• 推荐学习资源和方法\n", null);
            doc.insertString(doc.getLength(), "• 跟踪学习进度\n", null);
            doc.insertString(doc.getLength(), "• 提供学习建议和指导\n\n", null);
            doc.insertString(doc.getLength(), "请选择功能类别或直接输入您的问题！\n", null);
            doc.insertString(doc.getLength(), "========================================\n\n", null);
            chatArea.setCaretPosition(doc.getLength());
        } catch (BadLocationException e) {
            // 忽略异常
        }
    }

    private void sendMessage() {
        String message = inputField.getText().trim();
        if (message.isEmpty() || isStreaming)
            return;

        // 添加用户消息
        appendUserMessage("👤 您：" + message);

        // 添加AI助手标识
        appendAIMessage("🤖 AI助手：");

        // 记录AI响应的起始位置
        final int aiResponseStartPosition = chatArea.getDocument().getLength();

        // 禁用输入控件防止重复发送
        inputField.setEnabled(false);
        sendButton.setEnabled(false);
        isStreaming = true;

        // 获取当前分类
        String category = (String) categoryComboBox.getSelectedItem();

        // 使用流式传输调用AI API
        AIService.getChatResponseWithStreaming(message, category, new AIService.AIResponseCallback() {
            @Override
            public void onStreamStart() {
                // 流式传输开始
                appendAIMessage("正在思考...\n");
            }

            @Override
            public void onSuccess(String response) {
                // 流式传输结束，显示完整回复（如果需要）
                appendSeparator();

                // 重新启用输入控件
                inputField.setEnabled(true);
                sendButton.setEnabled(true);
                inputField.requestFocus();
                isStreaming = false;
            }

            @Override
            public void onError(String error) {
                // 清除之前的内容
                try {
                    StyledDocument doc = chatArea.getStyledDocument();
                    doc.remove(aiResponseStartPosition, doc.getLength() - aiResponseStartPosition);
                } catch (BadLocationException e) {
                    // 忽略异常
                }

                // 显示错误信息
                appendAIMessage("抱歉，AI服务暂时不可用：" + error + "\n");
                appendAIMessage("请稍后重试或尝试其他问题。\n");
                appendSeparator();

                // 重新启用输入控件
                inputField.setEnabled(true);
                sendButton.setEnabled(true);
                inputField.requestFocus();
                isStreaming = false;
            }

            @Override
            public void onProgress(String partialResponse) {
                // 实时更新流式响应
                try {
                    StyledDocument doc = chatArea.getStyledDocument();
                    // 清除之前的内容（从AI响应开始位置）
                    doc.remove(aiResponseStartPosition, doc.getLength() - aiResponseStartPosition);

                    // 使用Markdown解析器添加格式化内容
                    MarkdownParser.applyMarkdownToTextPane(chatArea, partialResponse);

                    // 滚动到底部
                    chatArea.setCaretPosition(chatArea.getDocument().getLength());

                } catch (BadLocationException e) {
                    // 如果出错，使用简单文本显示
                    try {
                        StyledDocument doc = chatArea.getStyledDocument();
                        doc.remove(aiResponseStartPosition, doc.getLength() - aiResponseStartPosition);
                        doc.insertString(doc.getLength(), partialResponse, null);
                        chatArea.setCaretPosition(chatArea.getDocument().getLength());
                    } catch (BadLocationException ex) {
                        // 忽略异常
                    }
                }
            }

            @Override
            public void onStreamEnd() {
                // 流式传输结束
            }
        });

        // 清空输入框
        inputField.setText("");
    }

    /**
     * 添加用户消息
     */
    private void appendUserMessage(String message) {
        try {
            StyledDocument doc = chatArea.getStyledDocument();
            doc.insertString(doc.getLength(), message + "\n\n", null);
            chatArea.setCaretPosition(doc.getLength());
        } catch (BadLocationException e) {
            // 忽略异常
        }
    }

    /**
     * 添加AI消息
     */
    private void appendAIMessage(String message) {
        try {
            StyledDocument doc = chatArea.getStyledDocument();
            doc.insertString(doc.getLength(), message, null);
            chatArea.setCaretPosition(doc.getLength());
        } catch (BadLocationException e) {
            // 忽略异常
        }
    }

    /**
     * 添加分隔符
     */
    private void appendSeparator() {
        try {
            StyledDocument doc = chatArea.getStyledDocument();
            doc.insertString(doc.getLength(), "\n\n----------------------------------------\n\n", null);
            chatArea.setCaretPosition(doc.getLength());
        } catch (BadLocationException e) {
            // 忽略异常
        }
    }

    private void handleQuickQuestion(String question) {
        inputField.setText(question);
        sendMessage();
    }

    /**
     * 创建样式化标签
     */
    private JLabel createStyledLabel(String text) {
        JLabel label = new JLabel(text);
        label.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        label.setForeground(new Color(75, 85, 99));
        return label;
    }

    /**
     * 现代化按钮样式（与统计页面一致）
     */
    private void styleModernButton(JButton button, Color backgroundColor) {
        button.setPreferredSize(new Dimension(90, 38));
        button.setBackground(backgroundColor);
        button.setForeground(Color.WHITE);
        button.setFont(new Font("Microsoft YaHei", Font.BOLD, 14));
        button.setBorder(BorderFactory.createEmptyBorder(10, 20, 10, 20));
        button.setFocusPainted(false);
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));

        // 悬停效果
        button.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                if (button.isEnabled()) {
                    button.setBackground(backgroundColor.darker());
                }
            }

            @Override
            public void mouseExited(java.awt.event.MouseEvent evt) {
                if (button.isEnabled()) {
                    button.setBackground(backgroundColor);
                }
            }
        });
    }

    /**
     * 美化按钮样式
     */
    private void styleButton(JButton button, Color backgroundColor, Color textColor) {
        button.setPreferredSize(new Dimension(80, 35));
        button.setBackground(backgroundColor);
        button.setForeground(textColor);
        button.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        button.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(backgroundColor.darker(), 1),
                BorderFactory.createEmptyBorder(6, 12, 6, 12)));
        button.setFocusPainted(false);
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));

        // 鼠标悬停效果
        button.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                if (button.isEnabled()) {
                    button.setBackground(backgroundColor.darker());
                }
            }

            @Override
            public void mouseExited(java.awt.event.MouseEvent evt) {
                if (button.isEnabled()) {
                    button.setBackground(backgroundColor);
                }
            }
        });
    }

    /**
     * 美化快捷功能按钮样式
     */
    private void styleQuickActionButton(JButton button, Color backgroundColor) {
        button.setPreferredSize(new Dimension(120, 40));
        button.setBackground(backgroundColor);
        button.setForeground(Color.WHITE);
        button.setFont(new Font("Microsoft YaHei", Font.PLAIN, 12));
        button.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(backgroundColor.darker(), 1),
                BorderFactory.createEmptyBorder(8, 12, 8, 12)));
        button.setFocusPainted(false);
        button.setCursor(new Cursor(Cursor.HAND_CURSOR));

        // 鼠标悬停效果
        button.addMouseListener(new java.awt.event.MouseAdapter() {
            @Override
            public void mouseEntered(java.awt.event.MouseEvent evt) {
                button.setBackground(backgroundColor.darker());
            }

            @Override
            public void mouseExited(java.awt.event.MouseEvent evt) {
                button.setBackground(backgroundColor);
            }
        });
    }

    /**
     * 美化输入框样式
     */
    private void styleTextField(JTextField textField) {
        textField.setPreferredSize(new Dimension(300, 35));
        textField.setFont(new Font("Microsoft YaHei", Font.PLAIN, 14));
        textField.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(209, 213, 219), 1),
                BorderFactory.createEmptyBorder(6, 12, 6, 12)));
        textField.setBackground(new Color(255, 255, 255));

        // 聚焦时的边框效果
        textField.addFocusListener(new java.awt.event.FocusListener() {
            @Override
            public void focusGained(java.awt.event.FocusEvent e) {
                textField.setBorder(BorderFactory.createCompoundBorder(
                        BorderFactory.createLineBorder(new Color(64, 158, 255), 2),
                        BorderFactory.createEmptyBorder(5, 11, 5, 11)));
            }

            @Override
            public void focusLost(java.awt.event.FocusEvent e) {
                textField.setBorder(BorderFactory.createCompoundBorder(
                        BorderFactory.createLineBorder(new Color(209, 213, 219), 1),
                        BorderFactory.createEmptyBorder(6, 12, 6, 12)));
            }
        });
    }

    /**
     * 美化组合框样式
     */
    private void styleComboBox(JComboBox<String> comboBox) {
        comboBox.setPreferredSize(new Dimension(120, 30));
        comboBox.setFont(new Font("Microsoft YaHei", Font.PLAIN, 13));
        comboBox.setBackground(new Color(255, 255, 255));
        comboBox.setBorder(BorderFactory.createCompoundBorder(
                BorderFactory.createLineBorder(new Color(209, 213, 219), 1),
                BorderFactory.createEmptyBorder(4, 8, 4, 8)));
    }
}
